import { readFileSync, writeFileSync } from 'node:fs'
import esbuild from 'esbuild'

function updateHTML() {
  const htmlFile = './examples/index.html'
  let html = readFileSync(htmlFile, { encoding: 'utf8' })
  html = html.replace(/\( 最近更新: [^\)]+ \)/, `( 最近更新: ${new Date().toLocaleString()} )`)
  writeFileSync(htmlFile, html, { encoding: 'utf8' })

  console.log('updated:', htmlFile)
}

export default function build(entry: string, out: string, watch: 'watching' | '' = '') {
  esbuild
    .context({
      entryPoints: [entry],
      bundle: true,
      minify: true,
      format: 'esm',
      external: ['three'],
      sourcemap: true,
      outfile: out,
    })
    .then((building) => {
      updateHTML()

      if (watch === 'watching') {
        console.log('watching:', out)
        building.watch()
      } else {
        console.log('done:', out)
        esbuild.stop()
      }
    })
    .catch(console.log)
}
